package com.wxh.bomb.netty.myrpc;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;
import java.util.UUID;

/**
 * RPC服务消费者
 * @author wxh
 */
public class RpcConsumer {

    /**
     * 动态代理实现远程调用
     * @param clz
     * @return
     */
    public static Object remote(final Class clz) {
        return Proxy.newProxyInstance(clz.getClassLoader(), new Class[]{clz}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Socket socket = new Socket("127.0.0.1", 8081);
                ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                // 将接口信息发送给服务，包含指纹信息，接口名 方法名称 参数类型 参数值
                out.writeUTF(UUID.randomUUID().toString());
                out.writeUTF(clz.getName());
                out.writeUTF(method.getName());
                out.writeObject(method.getParameterTypes());
                out.writeObject(args);
                out.flush();

                ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
                Object result = in.readObject();
                out.close();
                in.close();
                socket.close();
                return result;
            }
        });
    }

}
